import React,{ useState, useEffect, useLayoutEffect, axios } from "react";
import {Link,withRouter} from 'react-router-dom';
import './LeftNav.less';
// 订阅发布模块
import PubSub from 'pubsub-js';
// Antd组件库
import { Menu } from "antd";
import {
    BarChartOutlined,
    PictureOutlined,
    CodeOutlined,
    ProjectOutlined,
    ContainerOutlined,
    VideoCameraOutlined
} from "@ant-design/icons";

// Antd的子组件库解构
const { SubMenu } = Menu;

/**
 * 左侧导航组件
 */
function LefNav(props) {
    // 定义菜单主项的 Key 数组
    const rootSubMenuKeys = ['statistichome', 'pictures', 'plugins', 'projects', 'documentation', 'videos'];

    // 导航菜单项配置（通过异步去读取JSON文件的配置）
    const [menuList, setMenuList] = useState([]);

    // 获取当前页面的路由路径名
    let pathname = props.location.pathname + decodeURI(props.location.search);

    // 处理路由两次定向时可能定位到上级路由名的问题
    if(/^\/home\/?$/.test(pathname)) {
        pathname = '/home/statistichome';
    }

    // 页面刷新后需要展开的项目菜单 Key
    let needOpenMenuKey = pathname.match(/\/\w+/g)[1].slice(1);
    // 单独处理“统计和管理”的几个名称不一致的页面
    if(needOpenMenuKey === 'classifystatistic' ||
    needOpenMenuKey === 'resourcemanage') {
        // 都让第一个菜单展开
        needOpenMenuKey = 'statistichome';
    }

    // 定义默认选中的 Key
    const [openKeys, setOpenKeys] = useState([needOpenMenuKey]);
    
    // 定义一个开关监听函数
    const onOpenChange = keys => {
        const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1);
        if (rootSubMenuKeys.indexOf(latestOpenKey) === -1) {
            setOpenKeys(keys);
        } else {
            setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
        }
    };

    // 订阅左侧导航展开的事件
    const setOpenMenuToken = PubSub.subscribe('setOpenMenu', (meg, data) => {
        // 展开对应的导航栏
        setOpenKeys([data]);
    });

    /**
     * 生命周期函数：useEffect
     */
    useEffect(() => {
        
        // 组件卸载时执行（如前往了顶部导航的其它页面）
        return () => {
            PubSub.unsubscribe(setOpenMenuToken);
        }
    // pathname发生改变后需要重新更新组件
    }, [props.location.pathname, setOpenMenuToken]);

    /**
     * 生命周期函数：useLayoutEffect
     */
    useLayoutEffect(() => {
        // 利用这个同步的 Effect 生命周期来重绘左侧导航列表（防止出现死循环）
        // 请求导航列表的配置
        axios.get('/options/resource-manage-option.json')
            .then(res => {
                // 获取全部菜单导航分类
                const {resourceClassifyItems} = res.data;
                // 对全部菜单导航分类进行设置
                setMenuList(resourceClassifyItems)
            });
    }, []);

    return (
        <div className="LeftNav">
            {/* 导航列表 */}
            <Menu
                defaultSelectedKeys={[pathname]}
                selectedKeys={pathname}
                defaultOpenKeys={[needOpenMenuKey]}
                openKeys={openKeys}
                mode="inline"
                theme="dark"
                onOpenChange={onOpenChange}
            >
                <SubMenu
                    key="statistichome"
                    icon={<BarChartOutlined />}
                    title="统计和管理"
                >
                    <Menu.Item key="/home/statistichome">
                        <Link to="/home/statistichome">统计首页</Link>
                    </Menu.Item>
                    <Menu.Item key="/home/classifystatistic">
                        <Link to="/home/classifystatistic">分类统计</Link>
                    </Menu.Item>
                    <Menu.Item key="/home/resourcemanage">
                        <Link to="/home/resourcemanage">资源管理</Link>
                    </Menu.Item>
                </SubMenu>
                <SubMenu
                    key="pictures"
                    icon={<PictureOutlined />}
                    title="图片"
                >
                    {
                        menuList.length && menuList[0].subType ? 
                            menuList[0].subType.map(item => (
                                <Menu.Item key={"/home/pictures?classifyName=" + item}>
                                    <Link to={"/home/pictures?classifyName=" + item}>{item}</Link>
                                </Menu.Item>
                            )) : ''
                    }
                </SubMenu>
                <SubMenu
                    key="plugins"
                    icon={<CodeOutlined />}
                    title="插件库"
                >
                    {
                        menuList.length && menuList[1].subType ? 
                            menuList[1].subType.map(item => (
                                <Menu.Item key={"/home/plugins?classifyName=" + item}>
                                    <Link to={"/home/plugins?classifyName=" + item}>{item}</Link>
                                </Menu.Item>
                            )) : ''
                    }
                </SubMenu>
                <SubMenu
                    key="projects"
                    icon={<ProjectOutlined />}
                    title="项目存档"
                >
                    {
                        menuList.length && menuList[2].subType ? 
                            menuList[1].subType.map(item => (
                                <Menu.Item key={"/home/projects?classifyName=" + item}>
                                    <Link to={"/home/projects?classifyName=" + item}>{item}</Link>
                                </Menu.Item>
                            )) : ''
                    }
                </SubMenu>
                <SubMenu
                    key="documentation"
                    icon={<ContainerOutlined />}
                    title="资料文档"
                >
                    {
                        menuList.length && menuList[3].subType ? 
                            menuList[1].subType.map(item => (
                                <Menu.Item key={"/home/documentation?classifyName=" + item}>
                                    <Link to={"/home/documentation?classifyName=" + item}>{item}</Link>
                                </Menu.Item>
                            )) : ''
                    }
                </SubMenu>
                <SubMenu
                    key="videos"
                    icon={<VideoCameraOutlined />}
                    title="视频短片"
                >
                    {
                        menuList.length && menuList[4].subType ? 
                            menuList[1].subType.map(item => (
                                <Menu.Item key={"/home/videos?classifyName=" + item}>
                                    <Link to={"/home/videos?classifyName=" + item}>{item}</Link>
                                </Menu.Item>
                            )) : ''
                    }
                </SubMenu>
            </Menu>
        </div>
    );
}

export default withRouter(LefNav);
